module.exports = {
   initWebsocket: initWebsocket,
   onSocketMsg: onSocketMsg,
   loginWebsocket: loginWebsocket,
   sendSocketMsg: sendSocketMsg,
   sendToAll: sendToAll
}
var order_room_id = null
var myInvitedUserNotice = null
var WS_IsInitialized = 0   //ws是否已初始化
var co = require('common.js')
//初始化WS
function initWebsocket(userInfo, roomID, callback) {
   if (WS_IsInitialized) {
      //如果已初始化，不再初始化，只要登录
      callback('【websocket已初始化，登录中…】')
      loginWebsocket(userInfo, roomID, callback)
      return
   }
   wx.connectSocket({
      url: 'wss://ws.jyhs.ls293.cn',
      success: function (res) {
         console.log('【wx.connectSocket连接成功】')
         wx.onSocketOpen(function (res) {
            console.log('【wx.onSocketOpen打开成功】【初始化成功】')
            WS_IsInitialized = 1
            loginWebsocket(userInfo, roomID, callback)
         })
      },
      fail: function (res) {
         console.log('wx.connectSocket连接失败')
         initWebsocket(userInfo, roomID, callback)
      },
   })

   wx.onSocketClose(function (res) {
      WS_IsInitialized = 0
      console.log('【【wx.onSocketClose关闭了】】', res)
      setTimeout(function () {
         initWebsocket(userInfo, roomID, callback)
      }, 100)
   })
}
//用户登录WS
function loginWebsocket(userInfo, roomID, callback) {
   var json = {
      type: 'login',
      unionid: userInfo.unionid,
      client_name: userInfo.User_NickName,
      room_id: roomID
   }
   var msg = JSON.stringify(json)
   sendSocketMsg(msg, callback)
}
//发送信息到WS
function sendSocketMsg(msg, callback) {
   wx.sendSocketMessage({
      data: msg,
      success: function (res) {
         if (typeof (callback) == 'function') {
            callback(res)
         }
      },
      fail: function (res) {
         console.log('webSocket.js发送SocketMsg失败')
      },
   })
}

function sendToAll(content, callback) {
   var msg = {
      type: 'say',
      to_client_id: 'all',
      content: content
   }
   var msgJson = JSON.stringify(msg)
   sendSocketMsg(msgJson, callback)
}
function sendToAddFood(content, callback) {
   var msgJson = JSON.stringify(content)
   sendSocketMsg(msgJson, callback)
}
function onSocketMsg(callback) {
   wx.onSocketMessage(function (res) {
      var obj = JSON.parse(res.data)
      if (obj.type == 'ping') {
         sendSocketMsg(JSON.stringify({ type: 'pong' }))
      } else {
         callback(obj)
      }
   })
}
